package com.gitee.vueantd.upload.service.impl;

import com.gitee.vueantd.common.utils.PageUtil;
import com.gitee.vueantd.common.utils.QueryHelp;
import com.gitee.vueantd.common.utils.ValidationUtil;
import com.gitee.vueantd.upload.common.ProcessStatus;
import com.gitee.vueantd.upload.domain.UploadChunk;
import com.gitee.vueantd.upload.domain.UploadTaskData;
import com.gitee.vueantd.upload.repository.UploadTaskDataRepository;
import com.gitee.vueantd.upload.service.UploadTaskDataService;
import com.gitee.vueantd.upload.service.dto.UploadTaskDataQueryCriteria;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Set;

/**
 * @ClassName: UploadTaskDataServiceImpl
 * @Description: TODO
 * @Author: fuqiang zheng
 * @Date: 2021/5/6 11:15
 * @Version 1.0
 */
@Slf4j
@Service
public class UploadTaskDataServiceImpl implements UploadTaskDataService {

  @Autowired
  private UploadTaskDataRepository uploadTaskDataRepository;

  @Override
  public Object queryAll(UploadTaskDataQueryCriteria criteria, Pageable pageable) {
    return PageUtil.toPage(uploadTaskDataRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable));
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void delete(Set<Long> ids) {
    for (Long id : ids) {
      UploadTaskData task = findById(id);
      task.setStatus(ProcessStatus.DELETE);
      uploadTaskDataRepository.save(task);
    }
  }

  @Override
  public UploadTaskData findById(Long id) {
    UploadTaskData task = uploadTaskDataRepository.findById(id).orElseGet(UploadTaskData::new);
    ValidationUtil.isNull(task.getId(), "UploadTaskData", "id", id);
    return task;
  }

  @Override
  public UploadTaskData add(UploadChunk uploadChunk, File file, String newFileName) {
    if (file.length() == 0) { //如果文件大小为0，忽略
      log.error("文件上传[{}], 大小为0，忽略", uploadChunk.getFileName());
      return null;
    }
    UploadTaskData uploadTaskData = new UploadTaskData(uploadChunk.getFileType(), uploadChunk.getFileName());
    uploadTaskData.setNodeId(uploadChunk.getNodeId());
    uploadTaskData.setFilePath(file.getAbsolutePath());
    uploadTaskData.setExtraId(uploadChunk.getFileHash());
    uploadTaskData.setTaskUuid(uploadTaskData.buildTaskUuid());
    uploadTaskData.setUserName(uploadChunk.getUserName());
    uploadTaskData.setStatus(ProcessStatus.COMPLETED);
    UploadTaskData exists = uploadTaskDataRepository.findFirstByTaskUuid(uploadTaskData.getTaskUuid()).orElse(null);
    if (exists == null) {
      exists = uploadTaskDataRepository.save(uploadTaskData);
    }

    return exists;
  }
}